//
//  WQKImageViewer.m
//  test
//
//  Created by Zhuangyh on 15/12/27.
//  Copyright © 2015年 jaga. All rights reserved.
//

#import "WQKImageViewer.h"
@interface WQKImageViewer()<UIScrollViewDelegate>
@property(nonatomic,strong) UIPageControl *pageControl;
@property(nonatomic,assign) NSUInteger imagesCount;
@end

#define SCROLLVIEW  ((UIScrollView*)[super valueForKey:@"scrollView"])

@implementation WQKImageViewer

- (void)showWithImageViews:(NSArray*)views selectedView:(UIImageView*)selectedView {
    self.imagesCount = views.count;
    self.pageControl.numberOfPages = _imagesCount;
    self.pageControl.currentPage = [views indexOfObject:selectedView];
    UIView *bottomToolBar = [self pageControl];
    if (bottomToolBar) {
        if (![self.subviews containsObject:bottomToolBar]) {
            bottomToolBar.alpha = 0.0;
            [self addSubview:bottomToolBar];
        }
    }
    [super showWithImageViews:views selectedView:selectedView];
    SCROLLVIEW.delegate = self;
    [self insertSubview:self.pageControl atIndex:self.subviews.count-1];
    
    [self showPageControl];
}

- (UIPageControl *)pageControl {
    
    
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), 44)];
        _pageControl.numberOfPages = _imagesCount;
        _pageControl.alpha = 0.0;
        [self addSubview:_pageControl];
    }
    return _pageControl;
}

- (void)showPageControl {
    
    self.pageControl.frame= CGRectMake(0, CGRectGetHeight(self.bounds) , CGRectGetWidth(self.pageControl.bounds), CGRectGetHeight(self.pageControl.bounds));
    [UIView animateWithDuration:0.3+0.3 animations:^{
        UIView *bottomToolBar = [self pageControl];
        
        bottomToolBar.frame = CGRectMake(0, CGRectGetHeight(self.bounds) - CGRectGetHeight(bottomToolBar.bounds), CGRectGetWidth(bottomToolBar.bounds), CGRectGetHeight(bottomToolBar.bounds));
        bottomToolBar.alpha = 1.0;
    } completion:^(BOOL finished) {
        
    }];
}


- (void)dismissPageControl {
    [UIView animateWithDuration:0.3 animations:^{
        UIView *bottomToolBar = [self pageControl];
        bottomToolBar.frame = CGRectMake(0, CGRectGetHeight(self.bounds), CGRectGetWidth(bottomToolBar.bounds), CGRectGetHeight(bottomToolBar.bounds));
        bottomToolBar.alpha = 0.0;
    } completion:^(BOOL finished) {
        
    }];
}

- (NSInteger)pageIndex {
    return (SCROLLVIEW.contentOffset.x / SCROLLVIEW.frame.size.width);
}

#pragma mark - UIScrollView delegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    self.pageControl.numberOfPages = _imagesCount;
    self.pageControl.currentPage = [self pageIndex];
}

@end
